package com.sh.mytool.cv.service.impl;

import java.util.LinkedHashMap;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.sh.common.page.QueryResult;
import com.sh.mytool.cv.dao.BasicDao;
import com.sh.mytool.cv.domain.Image;
import com.sh.mytool.cv.domain.ImageFile;
import com.sh.mytool.cv.domain.ImageGallery;
import com.sh.mytool.cv.domain.ImageGalleryCover;
import com.sh.mytool.cv.service.ImageService;

@Service("imageService")
public class ImageServiceImpl implements ImageService {

	@Resource(name = "basicDao")
	private BasicDao<Image> dao;

	public BasicDao<Image> getDao() {
		return dao;
	}

	public void setDao(BasicDao<Image> dao) {
		this.dao = dao;
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public QueryResult<Image> page(Long galleryId, int begin, int max) {
		LinkedHashMap<String, Object> where = new LinkedHashMap<String, Object>();
		where.put("imageGallery.id", galleryId);
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		return dao.getScrollData(Image.class, begin, max, where, orderby);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void insert(ImageGallery gallery, Image image, ImageFile cover) throws Exception {
		if (cover != null) {
			cover.setImage(image);
			image.setImageFile(cover);
		}
		gallery.addImg(image);
		dao.insert(image);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void delete(Long id) throws Exception {
		dao.deleteById(Image.class, id);
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public Image get(Long id) {
		return dao.findById(Image.class, id);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void update(Image image, ImageFile cover) throws Exception {
		Image oldBean = this.get(image.getId());
		oldBean.setName(image.getName());
		if (cover != null) {
			// 不删除原先的，以后task每天定时删
			ImageFile oldCover = oldBean.getImageFile();
        	if(oldCover != null){
        		oldCover.setImage(null);
        	}
			cover.setImage(oldBean);
			oldBean.setImageFile(cover);
		}
		dao.update(oldBean);
	}

}
